//
//  AppDelegate+EaseMob.m
//  EasMobSample
//
//  Created by dujiepeng on 12/5/14.
//  Copyright (c) 2014 dujiepeng. All rights reserved.
//

#import "RomensAppDelegate+EaseMob.h"
#import <Hyphenate/EMSDK.h>
#import "ChatDemoHelper.h"
#import "HXRuntimeStatus.h"
#import <objc/runtime.h>
/**
 *  本类中做了EaseMob初始化和推送等操作
 */

@implementation RomensAppDelegate (EaseMob)
/**********************************************************************************/
/****** 初始化属性 ******************************************************************/
/**********************************************************************************/
//获取当前App的Application，launchOptions
static NSString *_appLctKey;
- (UIApplication *)hx_application {
    return objc_getAssociatedObject(self, &_appLctKey);
}
- (void)setHx_application:(UIApplication *)hx_application {
    objc_setAssociatedObject(self, &_appLctKey, hx_application, OBJC_ASSOCIATION_RETAIN);
}

static NSString *_launchOKey;
- (NSDictionary *)hx_launchOptions {
    return objc_getAssociatedObject(self, &_launchOKey);
}
- (void)setHx_launchOptions:(NSDictionary *)hx_launchOptions {
    objc_setAssociatedObject(self, &_launchOKey, hx_launchOptions, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
/**********************************************************************************/
/****** 方法 ******************************************************************/
/**********************************************************************************/

- (BOOL)HX_isAutoLogin {
    NSString *appKey = GetUserDefaults(HXAppkey);
    if (!isEmptyString(appKey)) {
        [self easemobApplication:self.hx_application didFinishLaunchingWithOptions:self.hx_launchOptions key:appKey];
        //获得当前环信的登录状态
        BOOL isLogin = [EMClient sharedClient].options.isAutoLogin;
        return isLogin;
    }
    return NO;
}
- (void)HX_initSDK {
    NSString *appKey = GetUserDefaults(HXAppkey);
    if (!isEmptyString(appKey)) {
        [self easemobApplication:self.hx_application didFinishLaunchingWithOptions:self.hx_launchOptions key:appKey];
        //获得当前环信的登录状态
        BOOL isLogin = [EMClient sharedClient].options.isAutoLogin;
        NSLog(@"login state:%@",isLogin?@"YES":@"NO");
    }
}

//环信推送// 将得到的deviceToken传给SDK，因为证书问题，非正式版，会获取设备的deviceToken失败
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//    [super application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
    NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
    NSString *dt = [token stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSString *dn = [dt stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [HXRuntimeStatus instance].pushToken= [dn stringByReplacingOccurrencesOfString:@" " withString:@""];
}
// 注册deviceToken失败，此处失败，与环信SDK无关，一般是您的环境配置或者证书配置有误
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    //refresh notification
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"apns.failToRegisterApns", Fail to register apns) message:error.description preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:NSLocalizedString(@"ok", @"OK") style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancle];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    //    NSLog(@"注册推送失败：%@",error.description);
}
#pragma mark -- 同步数据
- (void)HX_asynInitDataWithGroup:(BOOL)isSync {
    if (isSync == YES) {
        [[ChatDemoHelper shareHelper] asyncGroupFromServer];
    }
    [[ChatDemoHelper shareHelper] asyncConversationFromDB];
    [[ChatDemoHelper shareHelper] asyncPushOptions];
}
- (void)HX_asynInitData {
    [self HX_asynInitDataWithGroup:YES];
}
/********* 在桌面图标上显示未读消息数量 *****************************************************/
#pragma mark -- 在桌面上展示未读消息数量
- (void)HX_ShowIconBadgeNumber:(BOOL)isShow {
    if (isShow == YES) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupUnreadMessageCount) name:UnReadMsgsNotificationName object:nil];
    }
}
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }    
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:unreadCount];
}
/**************************************************************/
- (void)HX_AddNotificationHXLogin {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(RegisterLogin:)
                                                 name:HXnotificationName_Register
                                               object:nil];
}
//环信注册
-(void)RegisterLogin:(NSNotification *)notification{
    NSString *appKey = GetUserDefaults(HXAppkey);
    //    "HXAPPKEY":"romens#yyzsromens"
    if(!isEmptyString(appKey)){
        [self easemobApplication:self.hx_application didFinishLaunchingWithOptions:self.hx_launchOptions key:appKey];
    }
}

/**
 SDK注册：
 apnsCertName：APNS文件的名字；其他配置
 @param application application
 @param launchOptions launchOptions
 @param key 环信的appkey
 */
- (void)easemobApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions key:(NSString*)key {
    if (launchOptions) {
        NSDictionary*userInfo = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
        if(userInfo)
        {
            [self didReceiveRemoteNotification:userInfo];
        }
    }
#warning SDK注册 APNS文件的名字, 需要与后台上传证书时的名字一一对应
    NSString *apnsCertName = nil;
#if DEBUG
    apnsCertName = @"chatdemoui_dev";
#else
    apnsCertName = @"chatdemoui";
#endif
    [[EaseSDKHelper shareHelper] hyphenateApplication:application didFinishLaunchingWithOptions:launchOptions appkey:key apnsCertName:apnsCertName otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    
    [ChatDemoHelper shareHelper];
}
// 打印收到的apns信息
-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo
                                                        options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *str =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //refresh notification
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"推送内容" message:str preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:NSLocalizedString(@"ok", @"OK") style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancle];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
}


@end
